package com.work.leecode.dp.difficult;

/**
 * 接雨水-42
 */
public class Lc42 {
    //动态规划
    public int trap(int[] height) {
        int n = height.length;
        if (n == 0) {
            return 0;
        }

        //从左往右扫描，记录当前下标及其左侧的最大值
        int[] leftMax = new int[n];
        leftMax[0] = height[0];
        for (int i = 1; i < n; i++) {
            leftMax[i] = Math.max(leftMax[i - 1], height[i]);
        }

        //从右往左扫描，记录当前下标及其右侧的最大值
        int[] rightMax = new int[n];
        rightMax[n - 1] = height[n - 1];
        for (int j = n - 2; j >= 0; j--) {
            rightMax[j] = Math.max(rightMax[j + 1], height[j]);
        }

        //当前下标左右两侧较小的最大值-当前高度 = 雨水的体积
        int ans = 0;
        for (int i = 0; i < n; i++) {
            ans += Math.min(leftMax[i], rightMax[i]) - height[i];
        }
        return ans;
    }
}
